using System;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using System.Runtime.Serialization;
using EnvDTE;
using Microsoft.Practices.Common;
using Microsoft.Practices.RecipeFramework.Library.AssetReferences.UnboundReferences;
using Microsoft.Practices.RecipeFramework.Extensions.References.VisualStudio;

namespace Microsoft.Practices.RepositoryFactory.References
{
    /// <summary>
    /// UnBoundRecipeReference that allows to be executed only on a Vs Project, if the solution has a specified property
    /// </summary>
    [Serializable]
    public class ProjectSolutionPropertiesBasedReference : AnyProjectReference, IAttributesConfigurable 
    {
        private const string IsEnabledForPropertiesAttribute = "IsEnabledForProperties";
        private const string DefaultValueAttribute = "BoundIfPropertiesNotFound";
        private string propertiesName;
        private bool defaultValue;

        /// <summary>
        /// UnBoundRecipeReference that allows to be executed only on a Vs Project, if the solution has a specified property
        /// </summary>
        public ProjectSolutionPropertiesBasedReference(string recipe)
            : base(recipe)
        {
        }

        /// <summary>
        /// Returns a friendly name as Any project
        /// </summary>
        public override string AppliesTo
        {
            get { return Properties.Resources.ProjectReference; }
        }

        /// <summary>
        /// Performs the validation of the item passed as target
        /// Returns true if the reference is allowed to be executed in the target
        /// that is if the target is a project and if the solution has a specified property
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public override bool IsEnabledFor(object target)
        {
            Project project = target as Project;
            DTE dte = GetService<DTE>();
            bool response = defaultValue;
            string[] properties = propertiesName.Split('|');

            if (project == null)
                return false;

            for (int i = 0; i < properties.Length; i++)
            {
                if (dte.Solution.Globals.get_VariableExists(properties[i]))
                {
                    string propertyValue = (string)dte.Solution.Globals[properties[i]];
                    bool propertyValueBoolean;

                    if (Boolean.TryParse(propertyValue, out propertyValueBoolean))
                    {
                        response = propertyValueBoolean;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return response && base.IsEnabledFor(target);
        }

        #region ISerializable Members

        /// <summary>
        /// Required constructor for deserialization.
        /// </summary>
        protected ProjectSolutionPropertiesBasedReference(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            propertiesName = info.GetString(IsEnabledForPropertiesAttribute);
            defaultValue = info.GetBoolean(DefaultValueAttribute);
        }

        /// <summary>
        /// Provides a serialization member that derived classes can override to add
        /// data to be stored for serialization.
        /// </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the reference.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
        [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
        protected override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue(IsEnabledForPropertiesAttribute, propertiesName);
            info.AddValue(DefaultValueAttribute, defaultValue);
        }

        #endregion ISerializable Members

        #region IAttributesConfigurable Members

        /// <summary>
        /// Configures the component using the dictionary of attributes specified
        /// in the configuration file.
        /// </summary>
        /// <param name="attributes">The attributes in the configuration element.</param>
        public void Configure(System.Collections.Specialized.StringDictionary attributes)
        {
            if (attributes == null)
                throw new ArgumentNullException("attributes");

            if (attributes.ContainsKey(IsEnabledForPropertiesAttribute))
            {
                propertiesName = attributes[IsEnabledForPropertiesAttribute];
            }
            if (attributes.ContainsKey(DefaultValueAttribute))
            {
                bool.TryParse(attributes[DefaultValueAttribute], out defaultValue);
            }
        }

        #endregion
    }
}
